//
//  UIButton+Common.m
//  GeniusHelp_OC
//
//  Created by 8b410-2 on 16/10/18.
//  Copyright © 2016年 8b410-2. All rights reserved.
//

#import "UIButton+Common.h"
#import "UIImage+Common.h"
@implementation UIButton (Common)

+ (UIButton *)buttonWithImageNameStr:(NSString *)imageNameStr
                     BackgroundColor:(UIColor *)backgroundColor
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:[UIImage imageNamed:imageNameStr] forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageWithColor:backgroundColor] forState:UIControlStateNormal];
    return btn;
}

+ (UIButton *)buttonWithTitle:(NSString *)title
                   TitleColor:(UIColor *)titleColor
                     FontSize:(CGFloat)fontSize
              BackgroundColor:(UIColor *)backgroundColor
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [btn setBackgroundColor: [UIColor clearColor]];
    [btn setTitleColor:titleColor forState:UIControlStateNormal];
    [btn.titleLabel setFont:[UIFont systemFontOfSize:fontSize]];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageWithColor:backgroundColor] forState:UIControlStateNormal];
    return btn;
}


+ (UIButton *)buttonWithTitle:(NSString *)title
                   TitleColor:(UIColor *)titleColor
                     FontSize:(CGFloat)fontSize
                 ImageNameStr:(NSString *)imageNameStr
              BackgroundColor:(UIColor *)backgroundColor
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setTitleColor:titleColor forState:UIControlStateNormal];
    [btn.titleLabel setFont:[UIFont systemFontOfSize:fontSize]];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:imageNameStr] forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageWithColor:backgroundColor] forState:UIControlStateNormal];
    return btn;
}

- (void)verticalImageAndTitleWithSpacing:(CGFloat)spacing {
    CGSize imageSize = self.imageView.frame.size;
    CGSize titleSize = self.titleLabel.frame.size;
    CGSize textSize = [self.titleLabel intrinsicContentSize];
    CGSize frameSize = CGSizeMake(ceil(textSize.width), ceil(textSize.height));
    
    if (titleSize.width + 0.5 < frameSize.width) {
        titleSize.width = frameSize.width;
        CGRect titleFrame = self.titleLabel.frame;
        titleFrame.size = frameSize;
        [self.titleLabel setFrame:titleFrame];
    }
    
    CGFloat totalHeight = imageSize.height + textSize.height + spacing;
    CGFloat imageTop = -(totalHeight - imageSize.height);
    CGFloat imageRight = self.titleLabel.frame.origin.x >= self.frame.size.width ? 0 : -titleSize.width;
    self.imageEdgeInsets = UIEdgeInsetsMake(imageTop, 0, 0, imageRight);
    self.titleEdgeInsets = UIEdgeInsetsMake(0, -imageSize.width, -(totalHeight - textSize.height), 0);
    
}
@end
